package com.srwl.mytx.widget.chatRow;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.srwl.easeui.utils.EaseCommonUtils;
import com.srwl.mytx.R;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.IMThumbnailUtils;
import com.srwl.mytx.utils.ImageUtils;

import java.io.File;

public class ChatRowVideo extends ChatRowFile {

    private static final String TAG = "ChatRowVideo";
    private ImageView imageView;

    private TextView sizeView;

    private TextView timeLengthView;

    private ImageView playView;
    private BroadcastReceiver broadcastReceiver;

    public ChatRowVideo(View itemView) {
        super(itemView);


    }

    @Override
    protected void onInflateView() {

    }

    @Override
    protected void onUpdateView() {

    }

    @Override
    protected void onFindViewById(View itemView) {
        imageView = itemView.findViewById(R.id.chatting_content_iv);
        sizeView = itemView.findViewById(R.id.chatting_size_iv);
        timeLengthView = itemView.findViewById(R.id.chatting_length_iv);
        playView = itemView.findViewById(R.id.chatting_status_btn);
        percentageView = itemView.findViewById(R.id.percentage);
    }

    @Override
    protected void onSetUpView() {


        Integer playTime = message.getPlayTime();
        if (playTime != null && playTime > 0) {
            timeLengthView.setText(playTime.toString());
        }
        //imageView.setImageResource(R.drawable.ease_default_image);
//        if (!isSendMessage) {
//            if (message.getContent() != null && new File(message.getContent()).exists()) {
//                String size = EaseCommonUtils.getDataSize(new File(message.getContent()).length());
//                sizeView.setText(size);
//            }
//        }
        // GlideApp.with(context).load(message.getContent());
        if (isSendMessage) {
            handleSendMessage();
            //检测是否含有缩略图地址，没有就根据本地视频文件，生成缩略图
            String previewUrl = message.getPreviewUrl();
            if (TextUtils.isEmpty(previewUrl)) {
                String videoKey = message.getContent();
                String localPath;
                String localFilePath = message.getLocalFilePath();
                if (TextUtils.isEmpty(localFilePath)) {
                    //转发于 某条  接收消息
                    localPath = Helper.getInstance().getFilePath() + File.separator + videoKey;
                } else {
                    //原始发送消息 或者 转发于某条 发送消息
                    localPath = localFilePath;
                }
                genPreviewImage(localPath, videoKey != null ? videoKey : IDUtils.genUUID());
                messageDao.update(message);
            }
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            Integer height = message.getHeight();
            Integer width = message.getWidth();
            if (height != null && width != null) {
                layoutParams.height = height;
                layoutParams.width = width;

            } else {
                Log.i(TAG, "showImage: 图片尺寸为空" + message.toString());
            }
            if (GlideLoadUtils.isActivityAlive(activity)) {
                Glide.with(activity).load(previewUrl).diskCacheStrategy(DiskCacheStrategy.ALL).into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
            }
        } else {
            handleReceiveMessage();
        }
    }

    private void handleReceiveMessage() {

        String videoKey = message.getContent();
        Integer downloadState = message.getDownloadState();
        //如果下载状态为空，说明是第一次加载，设置下载状态为初始化
        if (downloadState == null) {
            downloadState = Constant.MESSAGE_DOWNLOAD_STATE_INIT;
        }
        switch (downloadState) {
            case Constant.MESSAGE_DOWNLOAD_STATE_INIT:
                Log.d(TAG, "初次加载视频文件:" + message.getId());
                imageView.setImageResource(R.drawable.ease_default_image);
                progressBar.setVisibility(View.VISIBLE);
                percentageView.setVisibility(View.VISIBLE);
                //又文件读写权限，才去下载文件，否则下载了保存也会报权限异常
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_LOADING);
                    downLoadVideoFile(videoKey);
                }
                break;
            case Constant.MESSAGE_DOWNLOAD_STATE_LOADING:
                imageView.setImageResource(R.drawable.ease_default_image);
                progressBar.setVisibility(View.VISIBLE);
                percentageView.setVisibility(View.VISIBLE);
                break;
            case Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS:
                percentageView.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.INVISIBLE);
                //再次检查本地文件是否存在
                File file = new File(Helper.getInstance().getFilePath(), videoKey);
                //检查文件是否存在，如果存在，就直接 返回true
                if (!file.exists()) {
                    Log.d(TAG, "文件不存在，再次加载视频文件:" + message.getId());
                    downLoadVideoFile(videoKey);
                    break;
                }
                //  String videoPath = Helper.getInstance().getFilePath() + File.separator + message.getContent();
                if (GlideLoadUtils.isActivityAlive(activity)) {

                    Glide.with(activity).load(message.getPreviewUrl()).diskCacheStrategy(DiskCacheStrategy.ALL).into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            imageView.setImageDrawable(resource);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
                }
                break;
            case Constant.MESSAGE_DOWNLOAD_STATE_FAIL:
                imageView.setImageResource(R.drawable.ease_default_image);
                percentageView.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.INVISIBLE);
                Integer reDownLoadCount = message.getReDownLoadCount();
                if (reDownLoadCount == null) {
                    reDownLoadCount = 0;
                }
                if (reDownLoadCount > 2) {
                    message.setReDownLoadCount(reDownLoadCount + 1);
                    Log.d(TAG, "加载视频文件失败重试:" + message.getId() + "当前重试次数：" + reDownLoadCount + 1);
                    progressBar.setVisibility(View.VISIBLE);
                    message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_LOADING);
                    downLoadVideoFile(videoKey);
                }
        }
    }

    private void downLoadVideoFile(String videoKey) {
        AliOssService.getInstance().downloadVideo(videoKey, new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        percentageView.setText(progress + "%");
                    }
                });
            }

            @Override
            public void onSuccess(String objectKey) {
                message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS);
                String localPath = Helper.getInstance().getFilePath() + File.separator + videoKey;
                genPreviewImage(localPath, videoKey);
                messageDao.update(message);
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyItemChanged(getAdapterPosition());
                    }
                });
            }

            @Override
            public void onFailure(String errorCode, String content) {
                message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_FAIL);
                messageDao.update(message);
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyItemChanged(getAdapterPosition());
                    }
                });
            }
        });
    }

    @Override
    protected void onBubbleClick() {
        if (itemClickListener != null) {
            Info smallImageViewInfo = PhotoView.getImageViewInfo(imageView);
            if (smallImageViewInfo == null) {
                return;
            }
            try {
                itemClickListener.onImageOrVideoRowClick(getAdapterPosition(), smallImageViewInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (message != null && !isSendMessage && chatRowCallBack != null) {
            chatRowCallBack.onMessageRead(message);
        }
    }


    public Info getImageRectInfo() {
        return PhotoView.getImageViewInfo(imageView);
    }


    /**
     * 根据原图生成预览图，并保存在本地
     *
     * @param videoKey
     */
    private void genPreviewImage(String localPath, String videoKey) {

        //根据预览图生成缩略图
        //如果出现内存溢出，可以用以下方法加载
        //com.srwl.mytx.utils.IMFileTools.decodeBitmapWithBestSampleSize
        Bitmap videoThumb = getVideoThumb(localPath);
        if (videoThumb == null) {
            Log.e(TAG, "genPreviewImage: 生成缩略图失败:" + localPath);
            return;
        }

//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(localPath, options);


        String previewPath = Helper.getInstance().getFilePath() + File.separator + "preview_" + videoKey;
        float scale = IMThumbnailUtils.getScale(videoThumb.getWidth(), videoThumb.getHeight(), context);

        if (scale != 1) {

            float scaleHeight = videoThumb.getHeight() * scale;
            float scaleWidth = videoThumb.getWidth() * scale;
            Bitmap scaleBitmap = IMThumbnailUtils.scaleBitmap((int) scaleWidth, (int) scaleHeight, true, videoThumb);
            message.setHeight((int) scaleHeight);
            message.setWidth((int) scaleWidth);
            if (scaleBitmap != null) {

                // IMFileTools.writeBitmap(previewPath, scaleBitmap, 100);
                boolean save = ImageUtils.save(scaleBitmap, previewPath, Bitmap.CompressFormat.JPEG, 90);
                if (!save) {
                    Log.e(TAG, "genPreviewImage: 保存缩略图失败  " + message.toString());
                    return;
                }
            } else {
                Log.e(TAG, "genPreviewImage: 生成缩略图失败 scaleBitmap 为空 " + message.toString());
                return;
            }

        } else {
            previewPath = localPath;
        }


        message.setPreviewUrl(previewPath);
    }

    private Bitmap getVideoThumb(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return media.getFrameAtTime();
    }
}
